package com.wbao.dianniu.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.CanDoBlankGridView;
import com.wbao.dianniu.customView.SpanTextView;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.data.TopData;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yejianjun on 2018/11/13.
 */

public class QaAddHeadAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {


    private Context mContext;
    private List<QaResponse> mList = new ArrayList<>();

    private static final int TYPE_ITEM = 0;
    private static final int TYPE_FOOTER = 1;
    private static final int TYPE_HEAD = 2;
    private static final int TYPE_AD = 3;
    //上拉加载更多
    public static final int PULLUP_LOAD_MORE = 0;
    //正在加载中
    public static final int LOADING_MORE = 1;
    //没有加载更多 隐藏
    public static final int NO_LOAD_MORE = 2;
    //上拉加载更多状态-默认为0
    private int mLoadMoreStatus = 0;
    LayoutInflater mInflater;
    /**
     * 事件回调监听
     */
    private OnItemClickListener mItemClickListener;


    /**
     * @param ctx
     */
    public QaAddHeadAdapter(Context ctx) {
        mContext = ctx;
        mInflater = LayoutInflater.from(ctx);
    }

    public void updateHeadInfo(int accountId, String nickName, String headPic, Integer sex, String label) {
        if (null == mList || mList.size() == 0) {
            return;
        }
        boolean isExist = false;
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).userInfo.accountId == accountId) {
                mList.get(i).userInfo.realName = nickName;
                mList.get(i).userInfo.headPic = headPic;
                mList.get(i).userInfo.sex = sex;
                mList.get(i).userInfo.label = label;
                isExist = true;
            }
        }
        if (isExist) {
            notifyDataSetChanged();
        }
    }

    public void updatePartner(int accountId, int partner) {
        if (null == mList || mList.size() == 0) {
            return;
        }
        boolean isExist = false;
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).userInfo.accountId == accountId) {
                mList.get(i).userInfo.partner = partner;
                isExist = true;
            }
        }
        if (isExist) {
            notifyDataSetChanged();
        }

    }

    public void setData(List<QaResponse> list) {
        if (null == mList) {
            mList = new ArrayList<>();
        }
        mList = list;
    }


    /**
     * 传入第一条非置顶数据的lastUpdateDate(去掉自己发的数据，自己发的lastUpdateDate为空)
     *
     * @return
     */
    public String getFirstUpdateDate() {
        if (null == mList || 0 == mList.size()) {
            return null;
        }
        String lastUpdateDate = null;
        for (int i = 0; i < mList.size(); i++) {
            if (null != mList.get(i).lastUpdateDate) {
                lastUpdateDate = mList.get(i).lastUpdateDate;
                break;
            }
        }
        return lastUpdateDate;
    }

    public String getLastUpdateDate() {
        if (null == mList || 0 == mList.size()) {
            return null;
        }
        return mList.get(mList.size() - 1).lastUpdateDate;
    }


    public void updateTopList(List<TopData> topDataList) {
        // 先清空原list的toplist
        removeTopList();
        for (int i = topDataList.size() - 1; i > -1; i--) {
            QaResponse qaResponse = new QaResponse();
            qaResponse.top = 1;
            qaResponse.content = topDataList.get(i).content;
            qaResponse.id = topDataList.get(i).id;
            mList.add(0, qaResponse);
        }
        notifyDataSetChanged();
    }

    public void removeTopList() {
        List<QaResponse> deList = new ArrayList<>();
        for (QaResponse response : mList) {
            if (null == response) {
                continue;
            }
            if (response.top == 1) {
                deList.add(response);
            } else {
                break;
            }
        }
        for (int i = 0; i < deList.size(); i++) {
            mList.remove(deList.get(i));
            notifyDataSetChanged();
        }
    }


    /**
     * 向前追加数据
     * 向前追加数据时，如果有需要去重的数据，需先去重数据，再追加数据
     *
     * @param list
     */
    public void addForwardList(List<QaResponse> list, List<TopData> topDataList) {
        if (null == mList) {
            mList = new ArrayList<>();
        }
        /*if (0 == list.size()) {
            return;
        }*/

        // 把topList中的数据也加入去重中...
        List<QaResponse> allList = new ArrayList<>();
        for (int i = 0; i < topDataList.size(); i++) {
            QaResponse qaResponse = new QaResponse();
            qaResponse.top = 1;
            qaResponse.content = topDataList.get(i).content;
            qaResponse.id = topDataList.get(i).id;
            allList.add(qaResponse);
        }
        if (null != list && list.size() > 0) {
            allList.addAll(list);
        }
        // 获取需要去重的数据列表
        List<QaResponse> deList = new ArrayList<>();
        for (QaResponse response : mList) {
            for (int i = 0; i < allList.size(); i++) {
                if (response.id == allList.get(i).id) {
                    deList.add(response);
                }
            }
        }

        for (int j = 0; j < deList.size(); j++) {
            mList.remove(deList.get(j));
            notifyDataSetChanged();
        }

        int index = getTopCounts();
        mList.addAll(index, list);
        notifyDataSetChanged();
    }

    /**
     * 向后追加数据
     *
     * @param list
     */
    public void addBackwardList(List<QaResponse> list) {
        if (null == mList) {
            mList = new ArrayList<>();
        }

        mList.addAll(mList.size(), list);
    }


    public List<QaResponse> getList() {
        return mList;
    }


    /**
     * 更新加载更多状态
     *
     * @param status
     */
    public void changeMoreStatus(int status) {
        mLoadMoreStatus = status;
        notifyDataSetChanged();
    }


    @Override
    public int getItemCount() {
        return mList.size() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        if (position + 1 == getItemCount()) {
            //最后一个item设置为footerView
            return TYPE_FOOTER;
        } else {
            if (mList.get(position).top == 1) {
                return TYPE_HEAD;
            } else if (mList.get(position).advert == 1) {
                return TYPE_AD;
            } else {
                return TYPE_ITEM;
            }
        }

    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.am_list_normal_item, parent, false);
            return new ItemViewHolder(view);
        } else if (viewType == TYPE_FOOTER) {
            View itemView = mInflater.inflate(R.layout.load_more_footview_layout, parent, false);
            return new FooterViewHolder(itemView);
        } else if (viewType == TYPE_HEAD) {
            View headView = mInflater.inflate(R.layout.am_list_top_item, parent, false);
            return new HeadViewHolder(headView);
        } else if (viewType == TYPE_AD) {
            View adView = mInflater.inflate(R.layout.am_list_ad_item, parent, false);
            return new AdViewHolder(adView);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof ItemViewHolder) {
            ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
            final QaResponse resp = mList.get(position);
            // 头像--名称--label sex partener addV 统一处理
            PictureDownloadUtils.displayHeadImage(mContext, itemViewHolder.userHolder.headIV, resp.userInfo.headPic);
            itemViewHolder.userHolder.nameTV.setText(resp.userInfo.realName == null ? "" : resp.userInfo.realName);
            itemViewHolder.userHolder.labelTV.setText(resp.userInfo.label == null ? "" : resp.userInfo.label);
            Utils.showSex(mContext, resp.userInfo.sex, itemViewHolder.userHolder.sexIV);
            Utils.showPartner(mContext, resp.userInfo.partner, itemViewHolder.userHolder.partnerIV);
            Utils.showAuth(resp.userInfo, itemViewHolder.userHolder.addV);

            itemViewHolder.contentTV.setEmojiText(resp.content, resp.noticeJson);
            // 问答
            itemViewHolder.userHolder.hotOrAdvertTV.setVisibility(View.GONE);
            // 删除按钮
            if (resp.accountId == GlobalContext.getAccountId()) {
                itemViewHolder.deleteTV.setVisibility(View.VISIBLE);
            } else {
                itemViewHolder.deleteTV.setVisibility(View.INVISIBLE);
            }
            //是否点赞
            if (0 == resp.isGood) {
                Drawable right_draw = mContext.getResources().getDrawable(R.drawable.click_praise_icon_nor);
                right_draw.setBounds(0, 0, right_draw.getMinimumWidth(), right_draw.getMinimumHeight());
                itemViewHolder.praiseTV.setCompoundDrawables(right_draw, null, null, null);
            } else {
                Drawable right_draw = mContext.getResources().getDrawable(R.drawable.click_praise_icon_sel);
                right_draw.setBounds(0, 0, right_draw.getMinimumWidth(), right_draw.getMinimumHeight());
                itemViewHolder.praiseTV.setCompoundDrawables(right_draw, null, null, null);
            }
            Utils.showPriseCounts(resp.goodCount, itemViewHolder.praiseTV);
            Utils.showPriseCounts(resp.answerCount, itemViewHolder.commentTV);

            if (TextUtils.isEmpty(resp.questImgs)) {
                itemViewHolder.gridview.setVisibility(View.GONE); // 没有图片资源就隐藏GridView
            } else {
                itemViewHolder.gridview.setVisibility(View.VISIBLE);
                Utils.showGridView(mContext, resp.questImgs, itemViewHolder.gridview, true, true);
            }

            //添加监听事件

            itemViewHolder.userHolder.headIV.setOnClickListener(this);
            itemViewHolder.userHolder.nameTV.setOnClickListener(this);
            itemViewHolder.contentTV.setOnClickListener(this);
            itemViewHolder.forwardTV.setOnClickListener(this);
            itemViewHolder.commentTV.setOnClickListener(this);
            itemViewHolder.praiseTV.setOnClickListener(this);
            itemViewHolder.deleteTV.setOnClickListener(this);
            itemViewHolder.amPicLayout.setOnClickListener(this);

            itemViewHolder.userHolder.headIV.setTag(R.id.user_head, position);
            itemViewHolder.userHolder.nameTV.setTag(R.id.user_name, position);
            itemViewHolder.contentTV.setTag(R.id.anonymous_content, position);
            itemViewHolder.forwardTV.setTag(R.id.include_forward_tv, position);
            itemViewHolder.commentTV.setTag(R.id.include_answer_tv, position);
            itemViewHolder.praiseTV.setTag(R.id.include_praise_tv, position);
            itemViewHolder.deleteTV.setTag(R.id.include_delete_tv, resp.id);
            itemViewHolder.amPicLayout.setTag(R.id.am_pic_layout, position);

        } else if (holder instanceof FooterViewHolder) {
            FooterViewHolder footerViewHolder = (FooterViewHolder) holder;
            switch (mLoadMoreStatus) {
                case PULLUP_LOAD_MORE:
                    footerViewHolder.mPbLoad.setVisibility(View.GONE);
                    footerViewHolder.mTvLoadText.setText("上拉加载更多...");
                    footerViewHolder.mLoadLayout.setVisibility(View.VISIBLE);
                    break;
                case LOADING_MORE:
                    footerViewHolder.mPbLoad.setVisibility(View.VISIBLE);
                    footerViewHolder.mTvLoadText.setText("正在加载...");
                    footerViewHolder.mLoadLayout.setVisibility(View.VISIBLE);
                    break;
                case NO_LOAD_MORE:
                    //隐藏加载更多
                    if (mList.size() >= 10) {
                        footerViewHolder.mTvLoadText.setText("没有更多数据");
                        footerViewHolder.mPbLoad.setVisibility(View.GONE);
                        footerViewHolder.mLoadLayout.setVisibility(View.VISIBLE);
                    } else {
                        footerViewHolder.mLoadLayout.setVisibility(View.GONE);
                    }
                    break;
                default:
                    break;
            }

        } else if (holder instanceof HeadViewHolder) {
            HeadViewHolder headViewHolder = (HeadViewHolder) holder;
            String tops = "<font color='#39bf9e'>置顶&#12288;</font>";
            headViewHolder.mTV.setText(Html.fromHtml(tops + mList.get(position).content));
            headViewHolder.mTV.setOnClickListener(this);
            headViewHolder.mTV.setTag(R.id.set_top_content_tv, position);

        } else if (holder instanceof AdViewHolder) {
            AdViewHolder adViewHolder = (AdViewHolder) holder;
            final QaResponse resp = mList.get(position);
            adViewHolder.userInfoHolder.nameTV.setText(resp.userInfo.realName);
            PictureDownloadUtils.displayHeadImage(mContext, adViewHolder.userInfoHolder.headIV, resp.userInfo.headPic);
            adViewHolder.contentTV.setEmojiText(resp.content, resp.noticeJson);

            adViewHolder.userInfoHolder.sexIV.setVisibility(View.VISIBLE);
            if (null == resp.userInfo.sex) {
                Utils.showSex(mContext, null, adViewHolder.userInfoHolder.sexIV);
            } else {
                Utils.showSex(mContext, resp.userInfo.sex, adViewHolder.userInfoHolder.sexIV);
            }
            Utils.showPartner(mContext, resp.userInfo.partner, adViewHolder.userInfoHolder.partnerIV);
            adViewHolder.userInfoHolder.labelTV.setVisibility(View.VISIBLE);
            adViewHolder.userInfoHolder.labelTV.setText(resp.userInfo.label == null ? "" : resp.userInfo.label);
            adViewHolder.userInfoHolder.addV.setVisibility(View.VISIBLE);
            Utils.showAuth(resp.userInfo, adViewHolder.userInfoHolder.addV);

            adViewHolder.userInfoHolder.hotOrAdvertTV.setText(mContext.getResources().getString(R.string.advert));
            adViewHolder.userInfoHolder.hotOrAdvertTV.setVisibility(View.VISIBLE);

            if (!TextUtils.isEmpty(resp.questImgs)) {   // 显示广告图
                Glide.with(mContext)
                        .load(GlobalContext.cdndownUrl + resp.questImgs)
                        .asBitmap()
                        .into(new AdViewTarget(adViewHolder.adIV));
            }
            adViewHolder.adIV.setOnClickListener(this);
            adViewHolder.contentTV.setOnClickListener(this);

            adViewHolder.adIV.setTag(R.id.anomyous_ad_pic_iv, position);
            adViewHolder.contentTV.setTag(R.id.ad_content_spanTV, position);
        }


    }

    private int getTopCounts() {
        int count = 0;
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).top == 1) {
                count++;
            } else {
                break;
            }
        }
        return count;
    }


    /**
     * 添加一条数据到最顶上，置顶数据下面
     *
     * @param addData
     * @return
     */
    public int addOneQuestData(QaResponse addData) {
        int index = getTopCounts();
        if (null != mList) {
            mList.add(index, addData);
            notifyDataSetChanged();
        }
        return index;
    }

    public void removeOneData(int id) {
        // TODO Auto-generated method stub
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == id) {
                mList.remove(i);
                notifyDataSetChanged();
                break;
            }
        }
    }

    public void priseNotify(int questId, int isGood, int goodCounts) {
        // TODO Auto-generated method stub
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == questId) {
                mList.get(i).isGood = isGood;
                mList.get(i).goodCount = goodCounts;
                notifyDataSetChanged();
                break;
            }
        }
    }

    public void replyNotify(int questId, int answerCounts) {
        // TODO Auto-generated method stub
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == questId) {
                mList.get(i).answerCount = answerCounts;
                notifyDataSetChanged();
                break;
            }
        }
    }

    public void updateVisitor(int questId, int visitorCounts) {
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == questId) {
                mList.get(i).visitorCount = visitorCounts;
                notifyDataSetChanged();
                break;
            }
        }
    }


    class ItemViewHolder extends RecyclerView.ViewHolder {
        //        private LinearLayout allLayout;
        UserInfoHolder userHolder;
        /**
         * 内容
         */
        public SpanTextView contentTV;
        /**
         * 转发数
         */
        public TextView forwardTV;
        /**
         * 点赞数
         */
        public TextView praiseTV;
        /**
         * 回复数
         */
        public TextView commentTV;
        /**
         * 删除
         */
        public TextView deleteTV;
        /**
         * 图片显示
         */
        public CanDoBlankGridView gridview;
        public LinearLayout amPicLayout;


        public ItemViewHolder(View convertView) {
            super(convertView);
            userHolder = new UserInfoHolder();
            userHolder.headIV = (ImageView) convertView.findViewById(R.id.user_head);
            userHolder.nameTV = (TextView) convertView.findViewById(R.id.user_name);
            userHolder.sexIV = (ImageView) convertView.findViewById(R.id.user_sex);
            userHolder.partnerIV = (ImageView) convertView.findViewById(R.id.user_partner);
            userHolder.hotOrAdvertTV = (TextView) convertView.findViewById(R.id.hot_advert_flag);
            userHolder.labelTV = (TextView) convertView.findViewById(R.id.user_label);
            userHolder.addV = (ImageView) convertView.findViewById(R.id.add_v_iv);
            contentTV = (SpanTextView) convertView.findViewById(R.id.anonymous_content);
            forwardTV = (TextView) convertView.findViewById(R.id.include_forward_tv);
            praiseTV = (TextView) convertView.findViewById(R.id.include_praise_tv);
            commentTV = (TextView) convertView.findViewById(R.id.include_answer_tv);
            deleteTV = (TextView) convertView.findViewById(R.id.include_delete_tv);
            gridview = (CanDoBlankGridView) convertView.findViewById(R.id.anony_gridview);
            amPicLayout = (LinearLayout) convertView.findViewById(R.id.am_pic_layout);
        }
    }


    class FooterViewHolder extends RecyclerView.ViewHolder {
        ProgressBar mPbLoad;
        TextView mTvLoadText;
        LinearLayout mLoadLayout;

        public FooterViewHolder(View itemView) {
            super(itemView);
            mPbLoad = (ProgressBar) itemView.findViewById(R.id.pbLoad);
            mTvLoadText = (TextView) itemView.findViewById(R.id.tvLoadText);
            mLoadLayout = (LinearLayout) itemView.findViewById(R.id.loadLayout);
        }
    }

    class HeadViewHolder extends RecyclerView.ViewHolder {
        TextView mTV;

        public HeadViewHolder(View view) {
            super(view);
            mTV = (TextView) view.findViewById(R.id.set_top_content_tv);
        }

    }

    class AdViewHolder extends RecyclerView.ViewHolder {
        UserInfoHolder userInfoHolder;
        /**
         * 内容
         */
        public SpanTextView contentTV;
        /**
         * 广告图片
         */
        public ImageView adIV;

        public AdViewHolder(View convertView) {
            super(convertView);
            userInfoHolder = new UserInfoHolder();
            userInfoHolder.headIV = (ImageView) convertView.findViewById(R.id.user_head);
            userInfoHolder.nameTV = (TextView) convertView.findViewById(R.id.user_name);
            userInfoHolder.sexIV = (ImageView) convertView.findViewById(R.id.user_sex);
            userInfoHolder.partnerIV = (ImageView) convertView.findViewById(R.id.user_partner);
            userInfoHolder.hotOrAdvertTV = (TextView) convertView.findViewById(R.id.hot_advert_flag);
            userInfoHolder.labelTV = (TextView) convertView.findViewById(R.id.user_label);
            userInfoHolder.addV = (ImageView) convertView.findViewById(R.id.add_v_iv);
            contentTV = (SpanTextView) convertView.findViewById(R.id.ad_content_spanTV);
            adIV = (ImageView) convertView.findViewById(R.id.anomyous_ad_pic_iv);
        }
    }

    @Override
    public void onClick(View v) {
        if (null != mItemClickListener)
            mItemClickListener.itemClick(v);
    }

    /**
     * 设置回调监听
     *
     * @param listener
     */
    public void setItemClickListener(OnItemClickListener listener) {
        mItemClickListener = listener;
    }

    public interface OnItemClickListener {
        void itemClick(View view);
    }


}
